package com.gaga.console.core.controller.sse;

import com.gaga.common.path.ApiPath;
import com.gaga.common.result.Result;
import com.gaga.console.base.controller.BaseController;
import com.gaga.console.base.utils.SseEmitterServerUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author liujia
 */
@Api(tags = "SSE接口")
@RequestMapping(ApiPath.ROOT + "/sse")
@RestController
@Slf4j
public class SseController extends BaseController {

    /**
     * 关闭连接
     */
    @ApiOperation("关闭SSE连接")
    @PostMapping("/close/{channelId}")
    public Result close(@ApiParam("频道ID") @PathVariable String channelId) {
        try {
            log.info("Closing SSE connection for channelId: {}", channelId);
            SseEmitterServerUtils.close(channelId);
            return Result.ok();
        } catch (Exception e) {
            log.error("Error closing SSE connection for channelId: {}, error: {}", channelId, e.getMessage());
            return Result.fail("关闭连接失败: " + e.getMessage());
        }
    }

    /**
     * SSE 接口，浏览器通过该接口接收消息
     *
     * @param channelId 屏幕ID
     */
    @ApiOperation("建立SSE连接")
    @GetMapping(path = "/connect/{channelId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(@ApiParam("频道ID") @PathVariable String channelId) {
        try {
            // 如果已经存在，则返回该连接
            SseEmitter existingEmitter = SseEmitterServerUtils.getId(channelId);
            if (existingEmitter != null) {
                log.info("Reusing existing SSE connection for channelId: {}", channelId);
                return existingEmitter;
            }

            log.info("Creating new SSE connection for channelId: {}", channelId);
            return SseEmitterServerUtils.connect(channelId);
        } catch (Exception e) {
            log.error("Error establishing SSE connection for channelId: {}, error: {}", channelId, e.getMessage());
            throw e;
        }
    }

    /**
     * 获取当前活跃连接数
     */
//    @ApiOperation("获取当前活跃连接数")
//    @GetMapping("/connections/count")
//    public Result getConnectionCount() {
//        try {
//            int count = SseEmitterServerUtils.getActiveConnectionCount();
//            log.info("Current active SSE connections: {}", count);
//            return Result.ok().data("count", count);
//        } catch (Exception e) {
//            log.error("Error getting connection count: {}", e.getMessage());
//            return Result.fail("获取连接数失败: " + e.getMessage());
//        }
//    }
}